package com.dongdongshop.controller;

import com.dongdongshop.ex.LoginException;
import com.dongdongshop.pojo.TbSeller;
import com.dongdongshop.service.SellerService;
import com.dongdongsop.data.AjaxResult;
import com.dongdongsop.em.ResultEnum;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("seller")
public class SellerController {

    @DubboReference
    private SellerService sellerService;

    //跳转商家后台注册页面
    @RequestMapping("toRegister")
    public String toRegister(){
        return "register";
    }

    //注册ID是否重复
    @RequestMapping("getInfoBySellerId")
    @ResponseBody
    public AjaxResult getInfoBySellerId(String sellerId){
        try {
            TbSeller seller = sellerService.getInfoBySellerId(sellerId);
            if (seller != null){
                return AjaxResult.OK().setData(seller);
            }else {
                return AjaxResult.ERROR();
            }
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.ERROR();
        }
    }

    //商家后台注册页面
    @RequestMapping("register")
    @ResponseBody
    public AjaxResult register(TbSeller seller){
        try {
            int i = sellerService.register(seller);
            return AjaxResult.OK().setData(i);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.ERROR();
        }
    }

    //跳转登录页面
    @RequestMapping("toLogin")
    public String toLogin(){
        return "shoplogin";
    }

    //跳转商家后台首页
    @RequestMapping("toIndex")
    public String toIndex(){
        return "admin/index";
    }

    //商家登录
    @RequestMapping("sellerLogin")
    @ResponseBody
    public AjaxResult sellerLogin(TbSeller seller){
        try {
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(seller.getSellerId(),seller.getPassword());
            try {
                subject.login(token);
            }catch (UnknownAccountException uae){
                return AjaxResult.R(ResultEnum.LOGIN_ERROR);
            }catch (IncorrectCredentialsException ice){
                ice.printStackTrace();
                return AjaxResult.R(ResultEnum.LOGIN_ERROR);
            }catch (LoginException le){
                le.printStackTrace();
                return AjaxResult.R(ResultEnum.NO_EXAMIN);
            }
            return AjaxResult.OK();
        }catch (Exception e){
            return AjaxResult.ERROR();
        }
    }
}
